package DynamicProxy;

import java.lang.reflect.Proxy;

/**
 * The `DynamicProxyExample` class demonstrates the use of Java's dynamic proxy mechanism to create a proxy instance
 * for a given service interface. This allows for the interception of method calls to the service, enabling additional
 * behavior such as logging, security checks, or transaction management without modifying the original service implementation.
 *
 * The class contains a `main` method that serves as the entry point for the demonstration. It performs the following steps:
 * 1. Creates an instance of the real service implementation (`RealService`).
 * 2. Constructs a dynamic proxy for the service using `Proxy.newProxyInstance`, which takes the class loader, interfaces,
 *    and an invocation handler (`LoggingHandler`) as arguments.
 * 3. Invokes a method on the proxy, which triggers the invocation handler to execute additional logic before or after
 *    delegating the call to the real service.
 *
 * The dynamic proxy mechanism is particularly useful for implementing cross-cutting concerns in a clean and modular way,
 * as it separates the core business logic from auxiliary functionalities.
 *
 * Note: This example assumes the existence of a `Service` interface, a `RealService` class implementing the interface,
 * and a `LoggingHandler` class that implements `InvocationHandler` to handle method calls on the proxy.
 */
public class DynamicProxyExample {
    /**
     * The main method serves as the entry point for the DynamicProxyExample application.
     * It demonstrates the use of Java's dynamic proxy mechanism to create a proxy instance
     * for a real service object, allowing for additional behavior (e.g., logging) to be
     * added to method calls without modifying the original service class.
     *
     * @param args Command-line arguments passed to the application. This parameter is not used in this implementation.
     */
    public static void main(String[] args) {
        Service realService = new RealService();

        // 创建动态代理
        Service proxy = (Service) Proxy.newProxyInstance(
                realService.getClass().getClassLoader(),
                realService.getClass().getInterfaces(),
                new LoggingHandler(realService)
        );

        proxy.doTask(); // 使用动态代理调用方法
    }
}
